package com.lyc.project.config;

import com.lyc.project.constant.TimeConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Exchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;

@Configuration
@Slf4j
public class RabbitmqConfig {
    
    // 正常队列
    public static final String QUEUE_ORDER = "queue_order";
    // 正常交换机
    public static final String EXCHANGE_ORDER ="exchange_order";
    // 正常路由
    public static final String ROUTINGKEY_ORDER ="routing.order";

    // 死信队列
    public static final String QUEUE_ORDER_DLX = "queue_order_dlx";
    // 死信交换机
    public static final String EXCHANGE_ORDER_DLX = "exchange_order_dlx";
    // 死信路由
    public static final String ROUTINGKEY_DLX_ORDER ="routing.dlx.order";


    //声明交换机
    @Bean(EXCHANGE_ORDER)
    public Exchange EXCHANGE_ORDER(){
        return new DirectExchange(EXCHANGE_ORDER,true,false);
    }

    //声明死信交换机
    @Bean(EXCHANGE_ORDER_DLX)
    public Exchange EXCHANGE_ORDER_DLX_EXCHANGE(){
        return new DirectExchange(EXCHANGE_ORDER_DLX,true,false);
    }

    //声明正常队列
    @Bean(QUEUE_ORDER)
    public Queue QUEUE_ORDER(){
        Map<String, Object> args = new HashMap<>(2);
        //正常队列中的消息被废弃后会被路由到死信队列(前提是有绑定死信队列)
        // 绑定死信交换机
        args.put("x-dead-letter-exchange", EXCHANGE_ORDER_DLX);
        // 绑定路由key
        args.put("x-dead-letter-routing-key", ROUTINGKEY_DLX_ORDER);
        // 设置过期时间
        args.put("x-message-ttl", TimeConstant.Expiration_Time);

        return new Queue(QUEUE_ORDER,true,false,false,args);
    }
    
    //声明死信队列
    @Bean(QUEUE_ORDER_DLX)
    public Queue QUEUE_ORDER_DLX_QUEUE(){
        return new Queue(QUEUE_ORDER_DLX,true,false,false);
    }

    
    //正常交换机绑定正常队列
    @Bean
    public Binding BINDING_QUEUE_ORDER(){
        return new Binding(QUEUE_ORDER,
                Binding.DestinationType.QUEUE, EXCHANGE_ORDER,
                ROUTINGKEY_ORDER,null);
    }

    //死信交换机绑定死信队列
    @Bean
    public Binding BINDING_DLX_QUEUE_ORDER(){
        return new Binding(QUEUE_ORDER_DLX,
                Binding.DestinationType.QUEUE, EXCHANGE_ORDER_DLX,
                ROUTINGKEY_DLX_ORDER,null);
    }
}
